package com.bonorsoft.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.bonorsoft.common.api.Result;
import com.bonorsoft.common.api.WilliamBootException;
import com.bonorsoft.config.properties.WeixinLoginProperties;
import com.bonorsoft.util.HttpRequest;
import com.bonorsoft.util.oConvertUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

/**
 * @description
 * @auth WilliamYe
 * @date 2021/8/31
 * @time 15:27
 */
@RestController
@Log4j2
public class ApiLoginController extends ApiBaseController {

    @GetMapping("/wxlogin")
    public Result<?> callback(String code){
        //判断code是否合法
        if(oConvertUtils.isEmpty(code)){
            throw new WilliamBootException("登录失败，请重新扫码登录");
        }
        //通过code获取access_token
        String baseAccessTokenUrl="https://api.weixin.qq.com/sns/jscode2session"
                + "?appid=%s"
                + "&secret=%s"
                + "&js_code=%s"
                + "&grant_type=authorization_code";
        log.info("appid-{}, appserct-{}", WeixinLoginProperties.WX_OPEN_APP_ID, WeixinLoginProperties.WX_OPEN_APP_SERCT);
        String accessTokenUrl = String.format(baseAccessTokenUrl, WeixinLoginProperties.WX_OPEN_APP_ID, WeixinLoginProperties.WX_OPEN_APP_SERCT, code);
        JSONObject result;
        try {
            //执行请求，获取微信请求返回结果
            result = HttpRequest.httpRequest(accessTokenUrl, "GET", null);
            if(result.getString("errcode") != null){
                throw new WilliamBootException("微信登录出错");
            }
            String openid = result.getString("openid");
            if (oConvertUtils.isEmpty(openid)){
                throw new WilliamBootException("登录失败，请重新扫码登录");
            }
            return Result.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(601, "微信解析失败");
        }
    }
}
